﻿using App_Start;
using BLL;
using Common.Class;
using Common.Model;
using Microsoft.AspNetCore.Mvc;

namespace RdpServer.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ClientKeyController : ControllerBase
    {
        /// <summary>
        /// 产生新的加密公钥和私钥
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CheckLocalFilter]
        [CheckLoginFilter]
        public ServiceResultModel ClientKeyCreate()
        {
            ServiceResultModel _rs = new ServiceResultModel() { Success = 0 };

            try
            {
                string _publicKey = "";
                string _privateKey = "";
                EncryptHelper.GenerateRSAKeyPair_RSA(out _publicKey, out _privateKey);

                _publicKey= StringHelper.Compress(_publicKey);
                _privateKey = StringHelper.Compress(_privateKey);

                ConfigBLL.Config.RSAPublicKey = _publicKey;
                ConfigBLL.Config.RSAPrivateKey = _privateKey;
                ConfigBLL.SaveConfig();


                _rs.Success = 1;
                _rs.Result = new { PublicKey = _publicKey };

            }
            catch (Exception ex)
            {
                string _errorID = Convert.ToString(CommonHelper.GetNewID(1));
                LogHelper.WriteLogToFile("Error", _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "");
                return new ServiceResultModel
                {
                    Success = -1,
                    ErrorMessage = "错误代码:" + _errorID
                };
            }

            return _rs;
        }

        /// <summary>
        /// 获取解密公钥
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [CheckLocalFilter]
        [CheckLoginFilter]
        public ServiceResultModel PublicKeyGet()
        {
            ServiceResultModel _rs = new ServiceResultModel() { Success = 0 };

            try
            {
                if (string.IsNullOrWhiteSpace(ConfigBLL.Config.RSAPublicKey))
                {
                    _rs.ErrorMessage = "密钥未生成，请初始化密钥";
                    return _rs;
                }

                _rs.Success = 1;
                _rs.Result = new { PublicKey = ConfigBLL.Config.RSAPublicKey };

            }
            catch (Exception ex)
            {
                string _errorID = Convert.ToString(CommonHelper.GetNewID(1));
                LogHelper.WriteLogToFile("Error", _errorID + "---" + ex.Message + "\r\n" + ex.StackTrace, "");
                return new ServiceResultModel
                {
                    Success = -1,
                    ErrorMessage = "错误代码:" + _errorID
                };
            }

            return _rs;
        }

    
    }
}
